<?php

class UsersController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/user';

	/**
	 * @return array action filters
	 */
     
    public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
    
    
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('birthday','index','view','viewprofiles'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','editprofiles','avatar','changepassword','changeemail'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
        if ($id === Yii::app()->user->id)
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}


	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Users']))
		{
			$model->attributes=$_POST['Users'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        if (Yii::app()->user->name === "admin")
        {
            $dataProvider=new CActiveDataProvider('Users');
            $this->render('index',array(
			     'dataProvider'=>$dataProvider,
            ));
        }
        else
        {
            $this->render('viewprofiles',array('model'=>$this->loadModelUserProfiles($this->id)));
        }
		
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Users('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Users']))
			$model->attributes=$_GET['Users'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Users::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
    public function Create ()
    {
        $model = new UserProfiles;
        $model->id = $model->user_id = Yii::app()->user->id;
        $model->display_name = Yii::app()->user->name;
        return $model;
    }
    
    public function loadModelUserProfiles ( $id )
    {   
       $model = UserProfiles::model()->findbyPk($id);
       if ($model === null)
            return $this->Create();
       else
            return $model;
    }
    
    public function actionEditprofiles ($id)
    {
        if (Yii::app()->user->id === $id) 
        {
            $model = $this->loadModelUserProfiles ($id);
            //$model->setScenario('avatar');

            if (isset ($_POST['UserProfiles']))
            {
                
                if(CUploadedFile::getInstance($model,'avatar')!=null)
                {
                    $model->attributes=$_POST['UserProfiles'];
                    $model->avatar =  CUploadedFile::getInstance($model,'avatar');
                    $name=$model->avatar;
                    $path = YiiBase::getPathOfAlias ('webroot').'/data/';
                    $model->avatar->saveAs($path.$name);
                }
                else
                {
                    $temp = $model->avatar;
                    $model->attributes=$_POST['UserProfiles'];
                    $model->avatar = $temp;
                }
                if ($model->save())
                {
                    $this->redirect (array('viewprofiles', 'id'=>$model->id));
                }
            }
            
            $this->render('_editprofiles',array('model'=>$model));
        }
 
    }
    
    public function actionAvatar ($id)
    {
        $model = $this->loadModelUserProfiles($id);
       $model->setScenario('avatar');
        if (isset($_POST['UserProfiles']))
			{
				$model->attributes = $_POST['UserProfiles'];
				$model->avatar = CUploadedFile::getInstance($model,'avatar'); // gan ten cua anh? vao $model->avatar de luu vao database
				if ($model->save())												// luu vao database.
				{
					$name = $model->avatar;										// gan ten anh? o trong database vao $name.
					$path = YiiBase::getPathOfAlias ('webroot').'/data/';		// duong dan toi thu muc chua anh?
					$model->avatar->saveAs($path.$name);						// con day la luu anh vao thu muc data.
				}
			}
         
        $this->render ('avatar',array('model'=>$model));
    }
    
    public function actionChangepassword($id)
    {
        if ($id === Yii::app()->user->id)
        {
            $model = $this->loadModel($id);
			$model->unsetattributes();
            $this->performAjaxValidation($model);
            $model->setScenario('changepassword');
            if (isset($_POST['Users']))
            {
                $model->attributes=$_POST['Users'];
                if ($model->save())
                    $this->redirect(Yii::app()->homeUrl);
            }
            
            $this->render('changepassword',array('model'=>$model));
        }
            
    }
    
    public function actionChangeemail($id)
    {
        if ($id === Yii::app()->user->id)
        {
                $model = $this->loadModel($id);
				$model->unsetattributes();
                $this->performAjaxValidation($model);
                $model->setScenario('changeemail');
                if (isset($_POST['Users']))
                {
                    foreach ($_POST['Users'] as $name=>$value)
                    {
                        if ($name==="password")
                        {
                            if ($this->equasPass($id,$value)===true)
                                $model->$name = $value;
                            else return $this->render('error');
                        }
                        if ($name!=="password") 
                            $model->$name=$value;
                    }
                    if ($model->save())
                        $this->redirect(Yii::app()->homeUrl);
                }
                $this->render('changeemail', array('model'=>$model));
        }
        
    }
    
    public function equasPass($id,$value)
    {
        $model = Users::model()->findByPk($id);
        if ($model->password === $model->MD5P($value))
            return true;
        else
            return false;
    }
    
    public function actionViewprofiles ($id)
    {
        $this->render('viewprofiles',array('model'=>$this->loadModelUserProfiles($id)));       
    }
    
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='users-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionBirthday()
	{
		$dataProvider = new CActiveDataProvider ('UserProfiles', array(
			'criteria'=>array(
				'condition'=>"YEAR(dob)=YEAR(UTC_DATE()) AND MONTH(dob)=MONTH(UTC_DATE())",
				'order'=>'display_name ASC',
			),
			'pagination'=>array(
				'pageSize'=>3,
			),
		));
		$this->render('indexprofiles', array('dataProvider'=>$dataProvider));
	}
}
